package com.example.musicdemo.widget

import android.content.Context
import android.graphics.Point
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.ListView
import android.widget.PopupWindow
import com.example.musicdemo.R
import org.jetbrains.anko.find

class PlayListPopWindow(
    context: Context, adapter: BaseAdapter,
    listener: AdapterView.OnItemClickListener, private val window: Window
) : PopupWindow() {
    private var alpha: Float = 0f

    init {
        //記錄當前窗體的透明度
        alpha = window.attributes.alpha
        //設置佈局
        val view = LayoutInflater.from(context).inflate(R.layout.pop_playlist, null, false)
        val lvPlayList = view.find<ListView>(R.id.lvPlayList)
        lvPlayList.adapter = adapter
        lvPlayList.onItemClickListener = listener
        contentView = view
        width = ViewGroup.LayoutParams.MATCH_PARENT
        //設置高度為屏幕高度的3/5
        val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        manager.defaultDisplay.getSize(point)
        val windowH = point.y
        height = (windowH * 3) / 5
        //設置獲取焦點
        isFocusable = true
        //設置外部點擊
        isOutsideTouchable = true
        //能夠響應返回按鈕
        setBackgroundDrawable(ColorDrawable())
        animationStyle = R.style.pop
    }


    override fun showAsDropDown(anchor: View?, xoff: Int, yoff: Int, gravity: Int) {
        super.showAsDropDown(anchor, xoff, yoff, gravity)
        //popWindow已經顯示
        val attributes = window.attributes
        attributes.alpha = 0.3f
        //設置到應用程序窗體上
        window.attributes = attributes
    }

    override fun dismiss() {
        super.dismiss()
        val attributes = window.attributes
        attributes.alpha = alpha
        window.attributes =attributes
    }
}